package logic

import (
	"2103A-server/house/house"
	"2103A-server/house/internal/svc"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"math"
	"net/http"
	"strconv"
)

type SelectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSelectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SelectLogic {
	return &SelectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SelectLogic) Select(in *house.SelectRequest) (*house.Response, error) {
	// todo: add your logic here and delete this line

	res, cnt, err := l.svcCtx.HouseModel.Paginate(context.Background(), in.Page, in.Limit, in.Keyword)

	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	p := cnt / in.Limit

	s := strconv.Itoa(int(p))
	f, err := strconv.ParseFloat(s, 10)
	pages := float32(math.Ceil(f))
	if pages == 0 {
		pages = 1
	}

	var rsp []*house.CreateRequest
	for _, v := range res {
		var item = &house.CreateRequest{
			Id:       v.Id,
			UserId:   v.UserId,
			Title:    v.Title,
			ImageUrl: v.IndexImageUrl,
		}
		rsp = append(rsp, item)
	}
	fmt.Println(rsp)
	return &house.Response{
		Code:  http.StatusOK,
		Msg:   "查询成功",
		Cnt:   cnt,
		Pages: pages,
		Data:  rsp,
	}, nil
}
